package main

import (
	"bufio"
	"fmt"
	"io"
	"io/ioutil"
	"os"
)

func main() {
	fd, err := os.OpenFile("testfile", os.O_CREATE|os.O_RDWR, 0644)
	if err != nil {
		panic(err)
	}

	length, err := fd.WriteString("write to testfile")
	if err != nil {
		panic(err)
	}
	fmt.Println("length:", length)

	_, err = fd.Seek(0, os.SEEK_SET)
	if err != nil {
		panic(err)
	}
	b := make([]byte, 1024)
	len2, err := fd.Read(b)
	if err != nil {
		panic(err)
	}

	fmt.Println("read buf :", string(b[:len2]))
	fd.Close()
	err = os.Remove("testfile")
	if err != nil {
		panic(err)
	}

	infile, err := os.Open("../LICENSE")
	if err != nil {
		panic(err)
	}
	defer infile.Close()
	//copy licence to copylicence
	r := bufio.NewReader(infile)

	oufile, err := os.OpenFile("copylicence", os.O_CREATE|os.O_RDWR, 0644)
	if err != nil {
		panic(err)
	}
	w := bufio.NewWriter(oufile)

	for {
		len1, err := r.Read(b)
		if err != nil && err != io.EOF {
			panic(err)
		}
		if len1 == 0 {
			break
		}
		len2, err := w.Write(b[:len1])
		if err != nil {
			panic(err)
		} else if len2 != len1 {
			fmt.Println("write error")
			os.Exit(1)
		}
	}
	if err = w.Flush(); err != nil {
		fmt.Println("flush error")
	}
	fmt.Println("first copy succ")
	oufile.Close()
	err = os.Remove("copylicence")
	if err != nil {
		panic(err)
	}

	//another way to copy

	data, err := ioutil.ReadFile("../LICENSE")
	if nil != err {
		panic(err)
	}
	err = ioutil.WriteFile("copy", data, 0644)
	if nil != err {
		panic(err)
	}
	fmt.Println("second copy succ")
	err = os.Remove("copy")
	if err != nil {
		panic(err)
	}
}
